package com.gf.framework.web.translate;

import com.gf.framework.common.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author gaofei
 * 添加自定义的转换器
 */
@Component
@Slf4j
public class TranslateConvertFactory implements SmartInitializingSingleton {
    @SuppressWarnings("all")
    private final Map<String, List<TranslateTypeConvert>> map = new HashMap<>();

    @SuppressWarnings("all")
    private final List<TranslateTypeConvert> defaultConverts = new ArrayList<>(1);

    public TranslateConvertFactory() {
        defaultConverts.add(new ObjectTypeConvert());
    }

    @SuppressWarnings("all")
    public List<TranslateTypeConvert> getTranslateTypeConvert(Class<?> convertClass) {
        return map.getOrDefault(convertClass.getName(), defaultConverts);
    }

    /**
     * 注册翻译器
     */
    @SuppressWarnings("all")
    @Override
    public void afterSingletonsInstantiated() {
        Map<String, TranslateTypeConvert> translateTypeConvertMap =
                SpringContextUtil.getContext().getBeansOfType(TranslateTypeConvert.class);
        if (CollectionUtils.isEmpty(translateTypeConvertMap)) {
            return;
        }

        translateTypeConvertMap.values().forEach(translateTypeConvert ->
                log.info("加载转义器: {}", translateTypeConvert.getClass()));

        translateTypeConvertMap.values().forEach(translateTypeConvert ->
                map.computeIfAbsent(translateTypeConvert.getTranslateType().getName(),
                        v->new ArrayList<>(defaultConverts)).add(translateTypeConvert));
        map.values().forEach(list -> list.sort(Comparator.comparingInt(TranslateTypeConvert::order)));
    }
}
